package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/v1/file")
public class UploadController {
    @PostMapping("/upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        log.debug("开始处理上传文件");
        String fileName = file.getOriginalFilename();
        log.debug("上传的文件名：{}", fileName);
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        log.debug("上传文件的后缀名：{}", suffix);
        String newFileName = UUID.randomUUID()+suffix;
        log.debug("上传的全新文件名：{}", newFileName);
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        log.debug("上传的日期路径：{}", datePath);
        String staticPath = "D:/files";
        File dirFile = new File(staticPath+datePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String path = staticPath+datePath+newFileName;
        file.transferTo(new File(path));
        //返回上传成功后的路径和文件名
        String datePathAndFileName = datePath+newFileName;
        return JsonResult.ok(datePathAndFileName);
    }
}
